/* eslint-disable @typescript-eslint/no-explicit-any */
// 此文件处理动态表结构，需要使用 any 类型

import type { PgTable } from 'drizzle-orm/pg-core';

/**
 * 审计字段类型
 */
export interface AuditFields {
  createdBy?: string;
  createdAt?: Date;
  updatedBy?: string;
  updatedAt?: Date;
  isDeleted?: boolean;
}

/**
 * 智能审计字段处理
 *
 * 自动检测表有哪些审计字段，只填充存在的字段
 *
 * @param table Drizzle 表定义
 * @param operation 操作类型
 * @param data 要插入/更新的数据
 * @param userId 当前用户 ID
 * @returns 添加了审计字段的数据
 *
 * @example
 * // 创建
 * await db.insert(sysUser).values(
 *   withAudit(sysUser, 'create', dto, userId)
 * );
 *
 * // 更新
 * await db.update(sysUser).set(
 *   withAudit(sysUser, 'update', dto, userId)
 * );
 *
 * // 软删除
 * await db.update(sysUser).set(
 *   withAudit(sysUser, 'delete', {}, userId)
 * );
 */
export function withAudit<T extends Record<string, any>>(
  table: PgTable,
  operation: 'create' | 'update' | 'delete',
  data: T,
  userId?: string
): T & Partial<AuditFields> {
  const result: any = { ...data };

  // Drizzle 表对象直接包含列定义
  const tableAny = table as any;

  // 创建操作：填充 createdBy
  if (operation === 'create') {
    if (tableAny.createdBy && userId) {
      result.createdBy = userId;
    }
    // createdAt 由数据库 defaultNow() 自动处理
  }

  // 更新或删除操作：填充 updatedAt, updatedBy
  if (operation === 'update' || operation === 'delete') {
    if (tableAny.updatedAt) {
      result.updatedAt = new Date();
    }
    if (tableAny.updatedBy && userId) {
      result.updatedBy = userId;
    }
  }

  // 删除操作：填充 isDeleted
  if (operation === 'delete') {
    if (tableAny.isDeleted) {
      result.isDeleted = true;
    }
  }

  return result;
}

/**
 * 简化方法：创建审计
 */
export function withCreateAudit<T extends Record<string, any>>(
  table: PgTable,
  data: T,
  userId?: string
): T & Partial<AuditFields> {
  return withAudit(table, 'create', data, userId);
}

/**
 * 简化方法：更新审计
 */
export function withUpdateAudit<T extends Record<string, any>>(
  table: PgTable,
  data: T,
  userId?: string
): T & Partial<AuditFields> {
  return withAudit(table, 'update', data, userId);
}

/**
 * 简化方法：软删除审计
 */
export function withSoftDeleteAudit(
  table: PgTable,
  userId?: string
): Partial<AuditFields> {
  return withAudit(table, 'delete', {}, userId);
}


